package net.xt.testthread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class TestLinkedBlockingQueue {
    public static void main(String[] args) {
        LinkedBlockingQueue<Object> queue = new LinkedBlockingQueue<>(5);

        // 生产者
        new Thread(() -> {
            while (true) {
                try {
                    queue.put("element");
                    System.out.println("生产一个元素，队列元素个数：" + queue.size());
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "生产者").start();

        // 消费者
        new Thread(() -> {
            while (true) {
                try {
                    Object object = queue.take();
                    System.out.println("消费一个元素" + object + "，队列元素个数：" + queue.size());
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "消费者").start();

    }

}
